package com.lvt.example.thinking.in.spring.data.binding;

import com.lvt.example.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;

import java.util.HashMap;
import java.util.Map;

/**
 * desc：{@link org.springframework.validation.DataBinder 示例}
 *
 * @author LT
 * @date 2022/6/4
 */
public class DataBinderDemo {

    public static void main(String[] args) {
        // 创建空白对象
        User user = new User();
        DataBinder dataBinder = new DataBinder(user);

        // 创建PropertyValues
        Map<String, Object> source = new HashMap<>();
        source.put("id", 1);
        source.put("name", "张三");

        // a. MutablePropertyValues 存在 User 中不存在的属性
        // 特性一：忽略不存在属性
        source.put("age", 14);

        // b. MutablePropertyValues 存在嵌套属性，比如：Company.name
        // 特性二：支持嵌套属性
        source.put("company.name", "公司");

        PropertyValues propertyValues = new MutablePropertyValues(source);

//        dataBinder.setIgnoreUnknownFields(false);

        // true->false 自动增加路径
        dataBinder.setAutoGrowNestedPaths(false);
        // false->true 默认不变化
        dataBinder.setIgnoreInvalidFields(true);

        dataBinder.setRequiredFields("id", "name");
//        dataBinder.setRequiredFields("id", "name", "city");


        dataBinder.bind(propertyValues);

        System.out.println(user);

        // 包含错误文案
        BindingResult bindingResult = dataBinder.getBindingResult();
        System.out.println(bindingResult);
    }
}
